package com.tools.scanner.ui.history.fragment

import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tools.scanner.BaseFragment
import com.tools.scanner.R
import com.tools.scanner.database.ScannerDatabase
import com.tools.scanner.databinding.FragmentCreateHistoryBinding
import com.tools.scanner.databinding.FragmentScannerHistoryBinding
import com.tools.scanner.ui.history.QrHistoryAdapter
import com.tools.scanner.ui.qrcode.CodeScannerResultActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CreateHistoryFragment : BaseHistoryFragment() {

    private lateinit var mBinding: FragmentCreateHistoryBinding

    private var mSearchContent = ""

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentCreateHistoryBinding.inflate(layoutInflater)
        return mBinding.root
    }

    private val mAdapter = QrHistoryAdapter() {
        CodeScannerResultActivity.actionStart(requireContext(), it)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.refreshLayout.setOnRefreshListener {
            search(mSearchContent)
        }

        mBinding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        mBinding.recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            private val margin = resources.getDimension(R.dimen.dp_10).toInt()
            override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
                if (itemPosition != 0) {
                    outRect.top = margin
                }

                outRect.left = margin
                outRect.right = margin
            }
        })
        mBinding.recyclerView.adapter = mAdapter
    }

    override fun onResume() {
        super.onResume()
        search(mSearchContent)
    }

    override fun search(content: String) {
        mSearchContent = content
        val query = if (content.isEmpty()) "" else "%$content%"

        mBinding.refreshLayout.isRefreshing = true
        lifecycleScope.launch(Dispatchers.IO) {
            val historyList = ScannerDatabase.get().searchQrHistory(1, query)
            withContext(Dispatchers.Main) {
                mBinding.refreshLayout.isRefreshing = false
                mAdapter.refresh(historyList)
            }
        }
    }

}










